from django.db import models
from django.utils import timezone
from user_management.models import CustomUser


class Environment(models.Model):
    """环境模型"""
    name = models.CharField(max_length=100, unique=True, verbose_name='环境名')
    description = models.TextField(blank=True, verbose_name='描述')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'environments'
        verbose_name = '环境'
        verbose_name_plural = '环境'

    def __str__(self):
        return self.name


class HostType(models.Model):
    """主机类型模型"""
    name = models.CharField(max_length=100, unique=True, verbose_name='类型名')
    description = models.TextField(blank=True, verbose_name='描述')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'host_types'
        verbose_name = '主机类型'
        verbose_name_plural = '主机类型'

    def __str__(self):
        return self.name


class HostGroup(models.Model):
    """主机组模型"""
    name = models.CharField(max_length=100, unique=True, verbose_name='组名')
    description = models.TextField(blank=True, verbose_name='描述')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'host_groups'
        verbose_name = '主机组'
        verbose_name_plural = '主机组'

    def __str__(self):
        return self.name


class Host(models.Model):
    """主机模型"""
    STATUS_CHOICES = [
        ('online', '在线'),
        ('offline', '离线'),
        ('maintenance', '维护中'),
        ('error', '异常'),
        ('checking', '检测中'),
    ]

    hostname = models.CharField(max_length=255, unique=True, verbose_name='主机名')
    ip_address = models.GenericIPAddressField(verbose_name='内网IP')
    public_ip = models.GenericIPAddressField(null=True, blank=True, verbose_name='公网IP')
    private_ip = models.GenericIPAddressField(null=True, blank=True, verbose_name='内网IP备用')

    # 系统信息
    os_type = models.CharField(max_length=50, blank=True, verbose_name='操作系统类型')
    os_version = models.CharField(max_length=100, blank=True, verbose_name='操作系统版本')
    kernel_version = models.CharField(max_length=100, blank=True, verbose_name='内核版本')
    cpu_cores = models.IntegerField(null=True, blank=True, verbose_name='CPU核心数')
    cpu_architecture = models.CharField(max_length=50, blank=True, verbose_name='CPU架构')
    memory_total = models.BigIntegerField(null=True, blank=True, verbose_name='总内存(MB)')
    memory_info = models.CharField(max_length=200, blank=True, verbose_name='内存信息')
    disk_total = models.BigIntegerField(null=True, blank=True, verbose_name='总磁盘(GB)')
    disk_info = models.CharField(max_length=200, blank=True, verbose_name='磁盘信息')

    # 关联关系
    environment = models.ForeignKey(Environment, on_delete=models.CASCADE, verbose_name='环境')
    host_type = models.ForeignKey(HostType, on_delete=models.CASCADE, verbose_name='主机类型')
    host_groups = models.ManyToManyField(HostGroup, blank=True, verbose_name='主机组')

    # 状态信息
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='offline', verbose_name='状态')
    last_check_time = models.DateTimeField(null=True, blank=True, verbose_name='最后检查时间')

    # SSH连接信息
    ssh_port = models.IntegerField(default=22, verbose_name='SSH端口')
    ssh_username = models.CharField(max_length=100, default='root', verbose_name='SSH用户名')
    ssh_password = models.CharField(max_length=255, blank=True, verbose_name='SSH密码')
    ssh_private_key = models.TextField(blank=True, verbose_name='SSH私钥')

    # 元数据
    description = models.TextField(blank=True, verbose_name='描述')
    created_by = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='创建者')
    created_at = models.DateTimeField(default=timezone.now, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'hosts'
        verbose_name = '主机'
        verbose_name_plural = '主机'

    def __str__(self):
        return f"{self.hostname} ({self.ip_address})"


class HostMonitorData(models.Model):
    """主机监控数据模型"""
    host = models.ForeignKey(Host, on_delete=models.CASCADE, verbose_name='主机')
    cpu_usage = models.FloatField(verbose_name='CPU使用率')
    memory_usage = models.FloatField(verbose_name='内存使用率')
    disk_usage = models.FloatField(verbose_name='磁盘使用率')
    network_in = models.BigIntegerField(verbose_name='网络入流量(bytes)')
    network_out = models.BigIntegerField(verbose_name='网络出流量(bytes)')
    load_average = models.FloatField(verbose_name='负载平均值')
    collected_at = models.DateTimeField(default=timezone.now, verbose_name='采集时间')

    class Meta:
        db_table = 'host_monitor_data'
        verbose_name = '主机监控数据'
        verbose_name_plural = '主机监控数据'
        ordering = ['-collected_at']


# DatabaseInstance 和 SQLAuditLog 模型已移动到 sql_management 应用中


class SSHConnectionLog(models.Model):
    """SSH连接日志"""
    host = models.ForeignKey(Host, on_delete=models.CASCADE, verbose_name='目标主机')
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='连接用户')

    # 连接信息
    source_ip = models.GenericIPAddressField(verbose_name='来源IP')
    user_agent = models.TextField(blank=True, verbose_name='用户代理')

    # 连接状态
    STATUS_CHOICES = [
        ('connecting', '连接中'),
        ('connected', '已连接'),
        ('disconnected', '已断开'),
        ('failed', '连接失败'),
    ]
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='connecting', verbose_name='连接状态')

    # 时间信息
    connect_time = models.DateTimeField(auto_now_add=True, verbose_name='连接时间')
    disconnect_time = models.DateTimeField(null=True, blank=True, verbose_name='断开时间')
    last_activity = models.DateTimeField(auto_now=True, verbose_name='最后活动时间')

    # 会话信息
    session_id = models.CharField(max_length=100, unique=True, verbose_name='会话ID')
    terminal_size = models.CharField(max_length=20, default='80x24', verbose_name='终端大小')

    # 统计信息
    commands_count = models.IntegerField(default=0, verbose_name='命令数量')
    bytes_sent = models.BigIntegerField(default=0, verbose_name='发送字节数')
    bytes_received = models.BigIntegerField(default=0, verbose_name='接收字节数')

    # 错误信息
    error_message = models.TextField(blank=True, verbose_name='错误信息')

    class Meta:
        verbose_name = 'SSH连接日志'
        verbose_name_plural = 'SSH连接日志'
        ordering = ['-connect_time']

    def __str__(self):
        return f"{self.user.username}@{self.host.hostname} - {self.status}"

    @property
    def duration(self):
        """连接持续时间"""
        if self.disconnect_time:
            return self.disconnect_time - self.connect_time
        return timezone.now() - self.connect_time


class SSHCommandLog(models.Model):
    """SSH命令执行日志"""
    connection = models.ForeignKey(SSHConnectionLog, on_delete=models.CASCADE, verbose_name='SSH连接')
    command = models.TextField(verbose_name='执行命令')
    output = models.TextField(blank=True, verbose_name='命令输出')
    exit_code = models.IntegerField(null=True, blank=True, verbose_name='退出码')
    execution_time = models.DateTimeField(auto_now_add=True, verbose_name='执行时间')
    duration = models.FloatField(null=True, blank=True, verbose_name='执行耗时(秒)')

    class Meta:
        verbose_name = 'SSH命令日志'
        verbose_name_plural = 'SSH命令日志'
        ordering = ['-execution_time']

    def __str__(self):
        return f"{self.connection.user.username}: {self.command[:50]}"
